﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using Caliburn.Core.Metadata;
using Caliburn.PresentationFramework.Actions;
using Caliburn.PresentationFramework.Metadata;
using Luna.WPF.ApplicationFramework;
using Microsoft.Practices.ServiceLocation;
using XWord.Common;
using XWord.Fundamental.Domain;
using XWord.GUI.Presenters.Interface;
using XWord.WPF.ApplicationFramework;
using XWord.WPF.ApplicationFramework.Extensions;
using XWord.WPF.ApplicationFramework.Threads;
namespace XWord.GUI.Presenters.Fundamental
{
  
    [Singleton("WordExplorer", typeof(IWordExplorerPresenter))]
    public class WordExplorerPresenter : DockingPresenter, IWordExplorerPresenter
    {
        
        private IServiceLocator _serviceLocator;
        public WordExplorerPresenter(IServiceLocator entityFactory)
        {
            _serviceLocator = entityFactory;
            this.DisplayName = "单词";
            
            //ThreadPool.QueueUserWorkItem(new WaitCallback((object obj) => {
            //    EntityList = BinaryFormatterHelper.Deserialize<IList<string>>(BinaryFiles.BaseWordDict)
            //        .Select(e => ParseWord(e)).ToDictionary(e=>e.Name);
            //    AllWordList = EntityList.Select(e => e.Key).OrderBy(e=>e).ToList();
                
            //}));
            //Application.Current.Exit += new ExitEventHandler(Current_Exit);
        }

        void Current_Exit(object sender, ExitEventArgs e)
        {
            var list = new List<string>(EntityList.Count);
            foreach (var item in EntityList)
            {
                var word=item.Value;
                var strArr = new string[]{word.Name,word.Comment,word.Pron,word.Suffix,
                    Convert.ToString(word.IsFamiliar),Convert.ToString(word.IsCET4),Convert.ToString(word.IsCET6)};
                list.Add(string.Join("|",strArr));
            }
            BinaryFormatterHelper.Serialize(BinaryFiles.BaseWordDict, list);
        }

        private Word ParseWord(string str)
        {
            var strArr = str.Split(new char[] { '|' });
            var word = new Word();
            word.Name = strArr[0];
            word.Comment = strArr[1];
            word.Pron = strArr[2];
            word.Suffix = strArr[3];
            word.IsFamiliar =Convert.ToBoolean(strArr[4]);
            word.IsCET4 = Convert.ToBoolean(strArr[5]);
            word.IsCET6 = Convert.ToBoolean(strArr[6]);
            return word;
        }

        private Dictionary<string,Word> _entityList;
        public Dictionary<string, Word> EntityList
        {
            get { return _entityList ?? (_entityList = new Dictionary<string, Word>()); }
            set
            {
                _entityList = value;
                NotifyOfPropertyChange("EntityList");
            }
        }

        private IList<string> _allWordList;
        public IList<string> AllWordList
        {
            get { return _allWordList ?? (_allWordList = new List<string>()); }
            set
            {
                _allWordList = value;
                NotifyOfPropertyChange("AllWordList");
            }
        }

        private IList<string> _wordList;
        public IList<string> WordList
        {
            get { return _wordList ?? (_wordList = new List<string>()); }
            set
            {
                _wordList = value;
                NotifyOfPropertyChange("WordList");
            }
        }

        [AsyncAction]
        public void SearchWord(string Name)
        {
            if (AllWordList == null) return;
            WordList = AllWordList.Where(WordSearchEngineFactory.GetDefaultSearch(Name.Trim())).ToObservableCollection();
        }

        private string _searchItem = string.Empty;
        public string SelectedItem
        {
            get { return _searchItem; }
            set
            {
                _searchItem = value;
                SelectedWord = EntityList[value];
                NotifyOfPropertyChange("SelectedItem");
                WordBehavior.RaiseWordEventHandler(SelectedWord, WordAction.SelectedItemChanged);
            }
        }

        public Word SelectedWord { get; set; }

        private bool _isOpen;
        public bool IsOpen
        {
            get { return _isOpen; }
            set
            {
                _isOpen = value;
                NotifyOfPropertyChange("IsOpen");
            }
        }

        private string _wordTip;
        public string WordTip
        {
            get { return _wordTip; }
            set
            {
                _wordTip = value;
                NotifyOfPropertyChange("WordTip");
            }
        }

        public IWordBehavior WordBehavior { get; set; }

        public WordTabPresenter WordTabPresenter { get; set; }

        public void CopyWordToSearch()
        {

            WordTabPresenter.SearchText = SelectedItem;
        }

        public void DeleteWord()
        {
            EntityList.Remove(this.SelectedItem);
            AllWordList.Remove(this.SelectedItem);
            WordList.Remove(SelectedItem);
            //Refresh();
            //WordBehavior.RaiseWordEventHandler(new Word() { Name = SelectedItem }, WordAction.Remove);
            //AllWordList.Remove(this.SelectedItem);
            //WordList.Remove(SelectedItem);
        }

        private void Refresh()
        {
            AllWordList = EntityList.Select(e => e.Key).OrderBy(e => e).ToList();

        }

        public void AddWord(IDataObject obj)
        {
            WordTip = "正在添加单词";
            IsOpen = true;

            var str = Convert.ToString(obj.GetData(DataFormats.UnicodeText));
            if (string.IsNullOrEmpty(str))
            {
                IsOpen = false;
                return;
            }
            WordImport import = new WordImport();
            import.ImportWord(str,
                (Word word) => { return !AllWordList.Any(ee => ee.Trim() == word.Name); },
                ((Word word) =>
                {
                    word.CreateTime = DateTime.Now;
                    EntityList[word.Name] = word;
                    AllWordList.Add(word.Name);
                    WordList.Insert(0, word.Name);
                    WordTip = string.Format("{0}添加成功", str);
                    GapDispatcherTimer.BeginInvoke(1, () =>
                    {
                        IsOpen = false;
                        //WordBehavior.RaiseWordEventHandler(word, WordAction.Add);
                    });
                }),
                ((Word word) =>
                {
                    WordTip = string.Format("{0}已经在列表中", str);
                    GapDispatcherTimer.BeginInvoke(1, () =>
                    {
                        IsOpen = false;
                    });
                }));
        }

        private Word InitWord(string name)
        {
            var word = new Word();
            word.Name = name;
            word.Comment = string.Empty;
            word.Pron = string.Empty;
            word.Suffix = string.Empty;
            return word;
        }


        public void AddAdornerToItemsSource(Adorner adorner)
        {
            AdornerLayer.GetAdornerLayer(AdornerElement).Add(adorner);
        }

        private ItemsControl _adornerElement;

        public ItemsControl AdornerElement
        {
            get
            {
                if (_adornerElement == null)
                {
                    var control = this.GetView<FrameworkElement>(null).FindVisualChild<ItemsControl>();
                    if (control != null)
                    {
                        _adornerElement = control;

                    }
                }
                return _adornerElement;
            }
            set
            {
                _adornerElement = value;
            }
        }

        private bool _isViewLoaded;
        public bool IsViewLoaded
        {
            get { return _isViewLoaded; }
            set
            {
                _isViewLoaded = value;
                NotifyOfPropertyChange("IsViewLoaded");
            }
        }

        public override void ViewLoaded(object view, object context)
        {
            base.ViewLoaded(view, context);
            IsViewLoaded = true;
        }


       
    }
}
